﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.Linq;

namespace Bing
{
    /// <summary>
    /// Contains an array of results returned for a request to the Spell <see cref="ApiHelper.SourceType"/>, as well as a property that indicates the total number of results.
    /// </summary>
    [DebuggerDisplay("Total={Total}, Results={Results.Count}, Errors={Errors.Count}")]
    public class SpellResponse : SearchResponseBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SpellResponse"/> class.
        /// </summary>
        public SpellResponse(XContainer element)
            : base(element)
        {
            Results = new List<SpellResult>();
        }

        /// <summary>
        /// Gets or sets the a number that represents an <b><i>estimate</i></b> of the total number of results returned by the <see cref="SearchRequest"/>.
        /// </summary>
        /// <value>Returns a number that represents an <b><i>estimate</i></b> of the total number of results returned by the <see cref="SearchRequest"/>.</value>
        public UInt32 Total { get; set; }

        /// <summary>
        /// Gets or sets the array of results returned for this <see cref="SearchRequest"/>.
        /// </summary>
        /// <value>Array of results returned for this <see cref="SearchRequest"/>.</value>
        public List<SpellResult> Results { get; set; }

        /// <summary>
        /// Parses the response from the Bing API.
        /// </summary>
        /// <param name="element">The XML from the Bing API</param>
        /// <returns>An <see cref="SpellResponse" /></returns>
        public static SpellResponse ParseElement(XContainer element)
        {
            SpellResponse spellResponse = new SpellResponse(element);
            if (spellResponse.Errors.Count > 0) return spellResponse;

            var spell = element.Element(XName.Get("Spell", ApiHelper.SpellNs));
            if (spell == null) return spellResponse;

            spellResponse.Total = ApiHelper.GetElementValueOrDefault<UInt32>(spell, "Total", ApiHelper.SpellNs);
            XElement spellResult = spell.Element(XName.Get("Results", ApiHelper.SpellNs));

            if (spellResult == null) return spellResponse;
            foreach (XElement result in spellResult.Elements(XName.Get("SpellResult", ApiHelper.SpellNs)))
            {
                string value = ApiHelper.GetElementValueOrDefault<string>(result, "Value", ApiHelper.SpellNs);
                spellResponse.Results.Add(new SpellResult { Value = value });
            }

            return spellResponse;
        }
    }
}
